package com.fintech.common.util;


import com.fintech.common.entity.ResultData;
import com.fintech.common.enums.ReturnCode;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

public class RedisUtils {
	private static RedisUtils redisUtils = new RedisUtils();
	
	public static String lockName = "moneySourceLockName";
	
	private RedisUtils(){
	}
	
	public static ResultData<?>  verifyUser(String accessToken,String idFintechUmUser,Class type){
		ResultData<Object> resultData = new ResultData<Object>();
		if(StringUtils.isEmpty(accessToken)||StringUtils.isEmpty(idFintechUmUser)){
			resultData.setErrorMessage("缺少用户编号或token值!");
			return resultData;
		}
		String userInfo = null;
		try {
			userInfo=getInstance().get(idFintechUmUser);
		} catch (Exception e) {
			// 兼容整合后因为redis反序列化问题
			RedisUtils.getInstance().del(idFintechUmUser);
			MarvelsLogUtil.getInstance().error("获取登录用户失败", e);
		}
		if(StringUtils.isEmpty(userInfo)){
			userInfo=getInstance().get(accessToken);
		}
		if(StringUtils.isEmpty(userInfo)){
			resultData.setResultCode(ReturnCode.tokenInvalid.getErrorCode());
			resultData.setMessage(ReturnCode.tokenInvalid.getErrorDescribe());
			return resultData;
		}
		JSONObject jsonObject =  JSONObject.fromObject(userInfo);
		if(!StringUtils.equals(jsonObject.getString("userType"), "3") ){//助理不做单点登录
			//如果token不一样则在另一台设备登录
			if(!accessToken.equals(jsonObject.get("token") )){
				resultData.setResultCode(ReturnCode.other_login.getErrorCode());
				resultData.setMessage(ReturnCode.other_login.getErrorDescribe());
				return resultData;
			}
		}
		
		getInstance().setex(idFintechUmUser, 15*24*60*60, userInfo);
		resultData.setData(JSONObject.toBean(jsonObject,type));
		return resultData;
	} 
	
	
	public static RedisUtils getInstance(){
		return redisUtils;
	}
	
	/**
	 * 返回1 获取到锁    返回0 没有获取到锁
	 * @param lockName   锁的名字
	 * @param consumerName  使用锁的人（占有锁的人）
	 * @return
	 */
	public Boolean isLockSuccess(String lockName, String consumerName){
		return CacheUtils.isNotLock(lockName, consumerName);
	}
	
	public void set(String key, String value){
		CacheUtils.cacheObject(key, value);
	}

	public Long incr(String key){
		return CacheUtils.increment(key, 1L);
	}
	
	
   public String get(String key){
        return CacheUtils.getCacheString(key);
    }
   
   public String setex(String key,int seconds,String value){
	   try {
		   CacheUtils.cacheString(key, value, seconds);
		   return "1";
	   } catch (Exception e) {
		   return "0";
	   }
   }
   
   public void del(String key){
	   CacheUtils.delete(key);
   } 
   
   public Boolean expire(String key, int seconds){
		return CacheUtils.setExpire(key, seconds);
	}
   
}
